import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Typography,
  Select,
  DatePicker,
  Space,
  Table,
  Progress,
  Tag,
  Avatar,
  Tooltip,
  Button,
  Spin,
  Empty,
  Divider
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  ShopOutlined,
  TrophyOutlined,
  DollarOutlined,
  UserOutlined,
  StarOutlined,
  RiseOutlined,
  FallOutlined,
  ExportOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ShopService } from '../../services/shopService';
import { Shop } from '../../types';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

interface ShopStats {
  totalProducts: number;
  totalOrders: number;
  totalSales: number;
  totalRevenue: number;
  rating: number;
  reviewCount: number;
  followersCount: number;
  conversionRate: number;
  averageOrderValue: number;
  returnRate: number;
}

interface ShopRanking {
  shopId: string;
  shopName: string;
  shopLogo: string;
  revenue: number;
  orders: number;
  rating: number;
  growth: number;
  rank: number;
}

interface ShopStatisticsState {
  loading: boolean;
  dateRange: [dayjs.Dayjs, dayjs.Dayjs];
  selectedShop: string;

  // 总体统计
  overallStats: {
    totalShops: number;
    activeShops: number;
    totalRevenue: number;
    totalOrders: number;
    averageRating: number;
    growthRate: number;
  };

  // 商店排行
  shopRankings: ShopRanking[];

  // 趋势数据
  revenueTrend: Array<{ date: string; revenue: number; orders: number }>;
  categoryStats: Array<{ category: string; revenue: number; count: number }>;

  // 商店列表
  shops: Shop[];
  selectedShopStats: ShopStats | null;
}

const ShopStatistics: React.FC = () => {
  const dispatch = useAppDispatch();

  const [state, setState] = useState<ShopStatisticsState>({
    loading: false,
    dateRange: [dayjs().subtract(30, 'day'), dayjs()],
    selectedShop: '',

    overallStats: {
      totalShops: 0,
      activeShops: 0,
      totalRevenue: 0,
      totalOrders: 0,
      averageRating: 0,
      growthRate: 0,
    },

    shopRankings: [],
    revenueTrend: [],
    categoryStats: [],
    shops: [],
    selectedShopStats: null,
  });

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '首页', path: '/' },
      { title: '商店管理', path: '/shops' },
      { title: '商店统计' },
    ]));

    loadShops();
    loadStatistics();
  }, [dispatch]);

  useEffect(() => {
    loadStatistics();
  }, [state.dateRange, state.selectedShop]);

  // 加载商店列表
  const loadShops = async () => {
    try {
      const response = await ShopService.getShops({ page: 1, limit: 1000 });
      setState(prev => ({
        ...prev,
        shops: response.data || [],
      }));
    } catch (error) {
      console.error('加载商店列表失败:', error);
    }
  };

  // 加载统计数据
  const loadStatistics = async () => {
    try {
      setState(prev => ({ ...prev, loading: true }));

      const [startDate, endDate] = state.dateRange;
      const params = {
        startDate: startDate.format('YYYY-MM-DD'),
        endDate: endDate.format('YYYY-MM-DD'),
        shopId: state.selectedShop || undefined,
      };

      // 并行加载多个统计数据
      const [
        overallStatsResponse,
        rankingsResponse,
        trendResponse,
        categoryResponse,
        shopStatsResponse
      ] = await Promise.all([
        ShopService.getOverallStats(params).catch(err => {
          console.error('获取总体统计失败:', err);
          return null;
        }),
        ShopService.getShopRankings(params).catch(err => {
          console.error('获取商店排行失败:', err);
          return null;
        }),
        ShopService.getRevenueTrend(params).catch(err => {
          console.error('获取营收趋势失败:', err);
          return null;
        }),
        ShopService.getCategoryStats(params).catch(err => {
          console.error('获取分类统计失败:', err);
          return null;
        }),
        state.selectedShop ? ShopService.getShopStats(state.selectedShop).catch(err => {
          console.error('获取商店统计失败:', err);
          return null;
        }) : Promise.resolve(null)
      ]);

      setState(prev => ({
        ...prev,
        overallStats: overallStatsResponse?.data || prev.overallStats,
        shopRankings: rankingsResponse?.data || [],
        revenueTrend: trendResponse?.data || [],
        categoryStats: categoryResponse?.data || [],
        selectedShopStats: shopStatsResponse?.data || null,
        loading: false,
      }));
    } catch (error) {
      console.error('加载统计数据失败:', error);
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 格式化数字
  const formatNumber = (num: number | string, precision: number = 0) => {
    const numValue = typeof num === 'number' ? num : parseFloat(num) || 0;
    if (numValue >= 10000) {
      return (numValue / 10000).toFixed(precision) + '万';
    }
    return numValue.toLocaleString();
  };

  // 格式化货币
  const formatCurrency = (amount: number) => {
    return `¥${formatNumber(amount, 2)}`;
  };

  // 获取增长率颜色和图标
  const getGrowthDisplay = (growth: number | string) => {
    const numGrowth = typeof growth === 'number' ? growth : parseFloat(growth) || 0;
    const isPositive = numGrowth >= 0;
    return {
      color: isPositive ? '#52c41a' : '#f5222d',
      icon: isPositive ? <RiseOutlined /> : <FallOutlined />,
      text: `${isPositive ? '+' : ''}${numGrowth.toFixed(1)}%`
    };
  };

  // 商店排行表格列
  const rankingColumns: ColumnsType<ShopRanking> = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      width: 60,
      render: (rank) => (
        <div style={{ textAlign: 'center', fontWeight: 'bold' }}>
          {rank <= 3 ? (
            <TrophyOutlined style={{
              color: rank === 1 ? '#ffd700' : rank === 2 ? '#c0c0c0' : '#cd7f32',
              fontSize: '16px'
            }} />
          ) : (
            rank
          )}
        </div>
      ),
    },
    {
      title: '商店',
      key: 'shop',
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar src={record.shopLogo} size={32} style={{ marginRight: 8 }} />
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.shopName}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              <StarOutlined style={{ color: '#faad14', marginRight: 4 }} />
              {typeof record.rating === 'number' ? record.rating.toFixed(1) : (parseFloat(record.rating) || 0).toFixed(1)}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '营业额',
      dataIndex: 'revenue',
      key: 'revenue',
      render: (revenue) => (
        <Text strong style={{ color: '#1890ff' }}>
          {formatCurrency(revenue)}
        </Text>
      ),
    },
    {
      title: '订单数',
      dataIndex: 'orders',
      key: 'orders',
      render: (orders) => formatNumber(orders),
    },
    {
      title: '增长率',
      dataIndex: 'growth',
      key: 'growth',
      render: (growth) => {
        const display = getGrowthDisplay(growth);
        return (
          <span style={{ color: display.color }}>
            {display.icon} {display.text}
          </span>
        );
      },
    },
  ];

  // 安全获取数组数据
  const revenueTrendData = Array.isArray(state.revenueTrend) ? state.revenueTrend : [];
  const categoryStatsData = Array.isArray(state.categoryStats) ? state.categoryStats : [];

  // 营收趋势图配置
  const getRevenueTrendOption = () => {
    if (revenueTrendData.length === 0) {
      return {
        title: { text: '暂无数据', left: 'center' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [{ data: [], type: 'line' }]
      };
    }

    return {
      title: {
        text: '营收趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: revenueTrendData.map(item => item.date || '')
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: revenueTrendData.map(item => item.revenue || 0),
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#1890ff'
        }
      }]
    };
  };

  // 分类统计饼图配置
  const getCategoryStatsOption = () => {
    if (categoryStatsData.length === 0) {
      return {
        title: { text: '暂无数据', left: 'center' },
        series: [{ type: 'pie', data: [] }]
      };
    }

    return {
      title: {
        text: '分类统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'pie',
        radius: '60%',
        data: categoryStatsData.map(item => ({
          name: item.category || '未知',
          value: item.revenue || 0
        }))
      }]
    };
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Title level={2}>商店统计</Title>
        <Space>
          <Select
            placeholder="选择商店"
            value={state.selectedShop}
            onChange={(value) => setState(prev => ({ ...prev, selectedShop: value }))}
            style={{ width: 200 }}
            allowClear
          >
            {state.shops.map(shop => (
              <Option key={shop._id} value={shop._id}>
                <Avatar src={shop.logo} size={16} style={{ marginRight: 8 }} />
                {shop.name}
              </Option>
            ))}
          </Select>
          <RangePicker
            value={state.dateRange}
            onChange={(dates) => {
              if (dates) {
                setState(prev => ({ ...prev, dateRange: dates as [dayjs.Dayjs, dayjs.Dayjs] }));
              }
            }}
          />
          <Button icon={<ReloadOutlined />} onClick={loadStatistics}>
            刷新
          </Button>
          <Button icon={<ExportOutlined />}>
            导出报告
          </Button>
        </Space>
      </div>

      <Spin spinning={state.loading}>
        {/* 总体统计卡片 */}
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="商店总数"
                value={state.overallStats.totalShops}
                prefix={<ShopOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="活跃商店"
                value={state.overallStats.activeShops}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总营业额"
                value={state.overallStats.totalRevenue}
                prefix={<DollarOutlined />}
                formatter={(value) => formatCurrency(Number(value))}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总订单数"
                value={state.overallStats.totalOrders}
                formatter={(value) => formatNumber(Number(value))}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="平均评分"
                value={state.overallStats.averageRating}
                precision={1}
                prefix={<StarOutlined />}
                valueStyle={{ color: '#eb2f96' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="增长率"
                value={state.overallStats.growthRate}
                precision={1}
                suffix="%"
                prefix={state.overallStats.growthRate >= 0 ? <RiseOutlined /> : <FallOutlined />}
                valueStyle={{
                  color: state.overallStats.growthRate >= 0 ? '#52c41a' : '#f5222d'
                }}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16}>
          {/* 左侧：营收趋势和分类统计 */}
          <Col span={16}>
            <Card title="营收趋势" style={{ marginBottom: 16 }}>
              <ReactECharts option={getRevenueTrendOption()} style={{ height: '300px' }} />
            </Card>

            <Card title="分类统计">
              <ReactECharts option={getCategoryStatsOption()} style={{ height: '300px' }} />
            </Card>
          </Col>

          {/* 右侧：商店排行和详细统计 */}
          <Col span={8}>
            <Card title="商店排行榜" style={{ marginBottom: 16 }}>
              <Table
                columns={rankingColumns}
                dataSource={state.shopRankings}
                rowKey="shopId"
                pagination={false}
                size="small"
                scroll={{ y: 400 }}
              />
            </Card>

            {/* 选中商店的详细统计 */}
            {state.selectedShopStats && (
              <Card title="商店详细统计">
                <Row gutter={[16, 16]}>
                  <Col span={12}>
                    <Statistic
                      title="商品数量"
                      value={state.selectedShopStats.totalProducts}
                      valueStyle={{ fontSize: '16px' }}
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="订单数量"
                      value={state.selectedShopStats.totalOrders}
                      valueStyle={{ fontSize: '16px' }}
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="销售额"
                      value={state.selectedShopStats.totalRevenue}
                      formatter={(value) => formatCurrency(Number(value))}
                      valueStyle={{ fontSize: '16px' }}
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="关注数"
                      value={state.selectedShopStats.followersCount}
                      valueStyle={{ fontSize: '16px' }}
                    />
                  </Col>
                </Row>

                <Divider />

                <div style={{ marginBottom: 16 }}>
                  <Text strong>转化率</Text>
                  <Progress
                    percent={state.selectedShopStats.conversionRate}
                    size="small"
                    style={{ marginTop: 4 }}
                  />
                </div>

                <div style={{ marginBottom: 16 }}>
                  <Text strong>退货率</Text>
                  <Progress
                    percent={state.selectedShopStats.returnRate}
                    status={state.selectedShopStats.returnRate > 10 ? 'exception' : 'normal'}
                    size="small"
                    style={{ marginTop: 4 }}
                  />
                </div>

                <Row gutter={16}>
                  <Col span={12}>
                    <Text type="secondary">平均订单价值</Text>
                    <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#1890ff' }}>
                      {formatCurrency(state.selectedShopStats.averageOrderValue)}
                    </div>
                  </Col>
                  <Col span={12}>
                    <Text type="secondary">评价数量</Text>
                    <div style={{ fontSize: '16px', fontWeight: 'bold' }}>
                      {formatNumber(state.selectedShopStats.reviewCount)}
                    </div>
                  </Col>
                </Row>
              </Card>
            )}
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default ShopStatistics;
